<template>
  <div class="module-card">
    <div class="module-header">
      <h3>部门简介管理</h3>
      <button 
        @click="isEditing = true" 
        class="btn-primary" 
        v-if="!isEditing"
        :class="{ 'pulse-effect': hovered }"
        @mouseenter="hovered = true"
        @mouseleave="hovered = false"
      >
        编辑简介
      </button>
    </div>
    
    <!-- 显示模式 -->
    <div class="intro-content" v-if="!isEditing" :class="{ 'fade-in': !isEditing }">
      <div v-if="deptIntro.description" class="intro-display">
        <div v-html="deptIntro.description" class="rich-content"></div>
      </div>
      <div v-else class="no-data">
        <div class="empty-state">
          <i class="icon-file-text-o"></i>
          <p>暂无部门简介数据</p>
        </div>
      </div>
      
      <!-- 图片上传区域 -->
      <div class="image-upload-section" v-if="!isEditing">
        <h4>部门图片：</h4>
        <div class="image-container">
          <div class="image-preview" v-if="displayImageUrl()">
            <img 
              :src="displayImageUrl()" 
              alt="部门图片" 
              class="preview-img"
              @click="showImagePreview = true"
            />
            <button 
              @click.stop="removeImage" 
              class="remove-img-btn"
              :class="{ 'show': imgHovered && deptIntro.imageUrl }"
              @mouseenter="imgHovered = true"
              @mouseleave="imgHovered = false"
            >
              <i class="icon-trash-o"></i>
            </button>
          </div>
          
          <div class="upload-placeholder" v-else>
            <i class="icon-upload"></i>
            <p>点击上传部门图片</p>
            <p class="hint-text">支持JPG、PNG格式，建议尺寸1200×600</p>
          </div>
          
          <button 
            @click="triggerImageUpload" 
            class="btn-primary upload-btn"
          >
            <i class="icon-picture-o"></i> 上传图片
          </button>
          <input 
            ref="imageInput" 
            type="file" 
            accept="image/*" 
            @change="handleImageUpload" 
            class="image-input"
          />
        </div>
      </div>
    </div>
    
    <!-- 编辑模式 -->
    <div class="intro-editor" v-if="isEditing" :class="{ 'slide-in': isEditing }">
      <textarea 
        v-model="editContent" 
        rows="10" 
        placeholder="请输入部门简介内容..."
        class="content-editor"
      ></textarea>
      <div class="editor-actions">
        <button @click="cancelEdit" class="btn-secondary">取消</button>
        <button @click="saveIntro" class="btn-primary">
          <i class="icon-save"></i> 保存
        </button>
      </div>
    </div>
    
    <!-- 图片预览弹窗 -->
    <div 
      class="image-modal" 
      v-if="showImagePreview && displayImageUrl()"
      @click="showImagePreview = false"
    >
      <div class="modal-content" @click.stop>
        <img :src="displayImageUrl()" alt="部门图片预览" class="modal-img" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import defaultDeptImage from '@/assets/主持.jpg'

// 状态管理
const deptIntro = ref({ content: '', description: '', imageUrl: '' })
const editContent = ref('')
const isEditing = ref(false)
const imageInput = ref(null)
const hovered = ref(false)
const imgHovered = ref(false)
const showImagePreview = ref(false)
const hasFetchedData = ref(false)

// 计算属性：获取图片URL，如果没有则使用默认图片
const displayImageUrl = () => {
  return deptIntro.value.imageUrl || defaultDeptImage
}

// 获取部门简介
const fetchDeptIntro = async () => {
  try {
    const response = await fetch('http://localhost:8080/department/3')
    const result = await response.json()
    if (result.code === 200) {
      deptIntro.value = result.data
      editContent.value = result.data.description || ''
      hasFetchedData.value = true
    } else {
      console.error('获取部门简介失败:', result.message)
      // 显示本地存储的历史数据（如果有）
      loadLocalBackup()
    }
  } catch (error) {
    console.error('获取部门简介失败:', error)
    // API调用失败时，尝试加载本地存储的备份数据
    loadLocalBackup()
    // 显示错误提示
    showToast('无法连接到服务器，正在使用本地数据', 'warning')
  }
}

// 加载本地备份数据
const loadLocalBackup = () => {
  try {
    const backup = localStorage.getItem('zhuchiDeptIntroBackup')
    if (backup) {
      const data = JSON.parse(backup)
      deptIntro.value = data
      editContent.value = data.description || ''
    }
  } catch (error) {
    console.error('加载本地备份数据失败:', error)
  }
}

// 保存数据到本地备份
const saveToLocalBackup = () => {
  try {
    localStorage.setItem('zhuchiDeptIntroBackup', JSON.stringify(deptIntro.value))
  } catch (error) {
    console.error('保存到本地备份失败:', error)
  }
}

// 保存部门简介
const saveIntro = async () => {
  try {
    const response = await fetch('http://localhost:8080/department/update', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        departmentId: 3,
        description: editContent.value
      })
    })
    
    const result = await response.json()
    if (result.code === 200) {
      deptIntro.value.description = editContent.value
      saveToLocalBackup()
      isEditing.value = false
      showToast('保存成功', 'success')
    } else {
      // 即使API失败，也保存到本地
      deptIntro.value.description = editContent.value
      saveToLocalBackup()
      isEditing.value = false
      showToast('无法连接到服务器，但已保存本地数据', 'warning')
    }
  } catch (error) {
    console.error('保存部门简介失败:', error)
    // 保存到本地
    deptIntro.value.description = editContent.value
    saveToLocalBackup()
    isEditing.value = false
    showToast('无法连接到服务器，但已保存本地数据', 'warning')
  }
}

// 图片上传相关
const triggerImageUpload = () => {
  imageInput.value.click()
}

const handleImageUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型和大小
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(file.type)) {
    showToast('请上传JPG、PNG或GIF格式的图片', 'warning')
    return
  }
  
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB', 'warning')
    return
  }

  // 本地预览功能 - 立即显示用户选择的图片
  const reader = new FileReader()
  reader.onload = (e) => {
    deptIntro.value.imageUrl = e.target.result
    saveToLocalBackup() // 保存到本地备份
  }
  reader.readAsDataURL(file)
  
  // 同时尝试上传到服务器
  const formData = new FormData()
  formData.append('image', file)
  formData.append('departmentId', 3)

  try {
    const response = await fetch('http://localhost:8080/department/uploadImage', {
      method: 'POST',
      body: formData
    })

    const result = await response.json()
    if (result.code === 200) {
      // 如果服务器返回了新的URL，使用服务器的URL
      deptIntro.value.imageUrl = result.data.imageUrl
      saveToLocalBackup()
      showToast('图片上传成功', 'success')
    } else {
      showToast(result.message || '图片上传失败，但已保存本地预览', 'warning')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    showToast('无法连接到服务器，但已保存本地预览', 'warning')
  }
  
  // 重置文件输入
  event.target.value = ''
}

// 移除图片
const removeImage = async () => {
  // 如果是默认图片，不执行删除操作
  if (!deptIntro.value.imageUrl) {
    showToast('默认图片无法删除', 'info')
    return
  }
  
  if (confirm('确定要删除这张图片吗？')) {
    try {
      const response = await fetch(`http://localhost:8080/department/removeImage?departmentId=3`, {
        method: 'DELETE'
      })
      
      const result = await response.json()
      if (result.code === 200 || !hasFetchedData.value) {
        // 如果是使用本地数据，也允许删除
        deptIntro.value.imageUrl = ''
        saveToLocalBackup()
        showToast('图片已删除', 'success')
      } else {
        showToast(result.message || '删除失败', 'error')
      }
    } catch (error) {
      console.error('删除图片失败:', error)
      // 即使API调用失败，如果是本地数据也允许删除
      if (!hasFetchedData.value) {
        deptIntro.value.imageUrl = ''
        saveToLocalBackup()
        showToast('已删除本地图片', 'success')
      } else {
        showToast('删除失败，请重试', 'error')
      }
    }
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  // 如果没有保存过，恢复到初始状态
  if (!hasFetchedData.value && deptIntro.value.description) {
    editContent.value = deptIntro.value.description
  }
}

// 提示框函数（假设全局可用）
const showToast = (message, type = 'info') => {
  // 这里假设项目中有全局的toast组件或函数
  console.log(`[${type}] ${message}`)
  // 实际项目中可能会调用如 this.$toast 或其他UI库的提示组件
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDeptIntro()
})
</script>

<style scoped>
/* 优化后的样式，增加尺寸和视觉效果 */
.module-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  overflow: hidden;
  margin-bottom: 24px;
  width: 100%;
  max-width: 1200px;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f7f7f7;
}

.module-header h3 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #333;
}

.btn-primary {
  background-color: #4096ff;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #59a2ff;
}

.pulse-effect {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 150, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 150, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 150, 255, 0);
  }
}

.intro-content {
  padding: 20px; /* 减少内边距 */
  transition: all 0.3s ease;
}

.fade-in {
  animation: fadeIn 0.5s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.intro-display {
  line-height: 1.6;
  color: #333;
}

.rich-content {
  min-height: 150px; /* 缩短最小高度 */
  font-size: 16px;
  line-height: 1.6;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  color: #999;
}

.empty-state {
  text-align: center;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #e0e0e0;
}

.image-upload-section {
  margin-top: 16px; /* 减少与内容区域的间距 */
}

.image-upload-section h4 {
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
}

.image-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.image-preview {
  position: relative;
  max-width: 100%;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.preview-img {
  width: 100%;
  height: auto;
  display: block;
  transition: transform 0.3s;
}

.preview-img:hover {
  transform: scale(1.02);
}

.remove-img-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(255, 255, 255, 0.7);
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s, background-color 0.3s;
}

.remove-img-btn.show {
  opacity: 1;
}

.remove-img-btn:hover {
  background-color: white;
}

.upload-placeholder {
  border: 2px dashed #e0e0e0;
  border-radius: 4px;
  padding: 20px; /* 减少内边距 */
  text-align: center;
  color: #999;
  min-height: 120px; /* 缩短占位符高度 */
}

.upload-placeholder i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #e0e0e0;
}

.hint-text {
  font-size: 12px;
  margin-top: 8px;
  color: #999;
}

.upload-btn {
  align-self: flex-start;
}

.image-input {
  display: none;
}

.intro-editor {
  padding: 20px;
  transition: all 0.3s ease;
}

.slide-in {
  animation: slideIn 0.3s;
}

@keyframes slideIn {
  from { transform: translateY(-10px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

.content-editor {
  width: 100%;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  min-height: 200px;
  box-sizing: border-box;
}

.content-editor:focus {
  outline: none;
  border-color: #4096ff;
  box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.2);
}

.editor-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-secondary:hover {
  background-color: #e9e9e9;
}

.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  max-width: 90%;
  max-height: 90%;
}

.modal-img {
  max-width: 100%;
  max-height: 100vh;
  display: block;
  margin: 0 auto;
}
</style>